import React from 'react';
import { useCallback, useContext, useEffect, useRef, useState } from 'react';
import { useRequest } from 'ahooks';
import { apiInterceptors, getApplogoList, uploadAppLogo, } from '@/client/api';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import Image from 'next/image';
import { useTranslation } from 'react-i18next';
import { logoUrl } from '@/utils';
import { userUpdate } from '@/client/api/login';
import { ChatContext } from '@/app/chat-context';
import { cloneDeep } from 'lodash';
import { Edge } from '@antv/x6';
import { Button, Form, Input, Modal, Spin, Select, Space, message } from 'antd';
import Icon, { LoadingOutlined, PlusOutlined, MinusCircleOutlined } from '@ant-design/icons';
const { Option } = Select;



const joinOptions = [
  {
    "label": "INNER_JOIN",
    "value": "INNER_JOIN"
  },
  {
    "label": "LEFT_JOIN",
    "value": "LEFT_JOIN"
  },
  {
    "label": "RIGHT_JOIN",
    "value": "RIGHT_JOIN"
  },
  {
    "label": "FULL_JOIN",
    "value": "FULL_JOIN"
  },
];
const symbolOptions = [
  {
    "label": "=",
    "value": "="
  },
];


const edgeModal: React.FC<{
  form: any;
  open: boolean;
  onCancel: (data: Edge) => void;
  onOk: (data: Edge) => void;
  type?: 'add' | 'edit';
}> = ({ form, open, onCancel, onOk, type = 'add', }) => {
  const { t, i18n } = useTranslation();
  const [loading, setLoading] = useState(false);
  const [sourceOptions, setSourceOptions] = useState<any[]>([
    // { label: 'customer_index', value: 'customer_index' },
    // { label: 'customer_index2', value: 'customer_index2' },
  ]);
  const [targetOptions, setTargetOptions] = useState<any[]>([
    // { label: 'orders', value: 'orders' },
    // { label: 'orders2', value: 'orders2' },
  ]);
  const [lFieldsOptions, setLFieldsOptions] = useState<any[]>([
    // { label: 'customer_id', value: 'customer_id' },
    // { label: 'customer_name', value: 'customer_name' },
    // { label: 'customer_address', value: 'customer_address' },
    // { label: 'customer_phone', value: 'customer_phone' },
    // { label: 'customer_email', value: 'customer_email' },
  ]);
  const [rFieldsOptions, setRFieldsOptions] = useState<any[]>([
    // { label: 'order_id', value: 'order_id' },
    // { label: 'order_date', value: 'order_date' },
    // { label: 'order_amount', value: 'order_amount' },
    // { label: 'order_status', value: 'order_status' },
    // { label: 'order_customer_id', value: 'order_customer_id' },
  ]);
  useEffect(() => {
    const sourceData = form.getSourceCell().getData();
    const targetData = form.getTargetCell().getData();
    setSourceOptions([{ ...sourceData.tableOrSqlOptionsCurrentInfo }]);
    setTargetOptions([{ ...targetData.tableOrSqlOptionsCurrentInfo }]);
    setLFieldsOptions((sourceData?.fieldList || []).map((item: any) => ({ ...item, label: item.field, value: item.field })));
    setRFieldsOptions((targetData?.fieldList || []).map((item: any) => ({ ...item, label: item.field, value: item.field })));
    const { join, fields } = form.getData() || {}

    // console.log('sourceData, targetData,', form.getData(), sourceData, targetData,)
    formData.setFieldsValue({
      sourceData: sourceData.id, targetData: targetData.id, join, fields: fields || [],
      sourceTableOrSql: sourceData.tableOrSqlOptionsCurrentInfo?.label, targetTableOrSql: targetData.tableOrSqlOptionsCurrentInfo?.label,
    });
  }, [form])

  const [formData] = Form.useForm();
  const onFinish = async () => {
    const params = formData.getFieldsValue();
    // console.log('params', params)
    if (!params.join) {
      message.error(t('w_checkJoin'));
      return;
    }
    if (!params.fields?.length) {
      message.error(t('w_join'));
      return;
    }
    const item = params.fields.filter(Boolean).find((item: any) => !item?.lField || !item?.rField)
    if (item) {
      message.error(t('w_checkFieldisempty'));
      return;
    }
    const data: any = { edge: form, formData: params };
    onOk(data);
    // console.log('formData', formData, params)
  };

  const handleChange = () => {
  };
  return <Modal title={t('w_connected')}
    width={500} open={open} onOk={onFinish}
    onCancel={() => onCancel(form)}>
    <Spin spinning={loading}>

      <Form form={formData} name="dynamic_form_complex" onFinish={onFinish} autoComplete="off">
        <div className='flex items-center'>
          <Form.Item style={{ display: 'none' }} name="sourceData" label="" rules={[{ required: true, message: 'Missing sourceData' }]}>
            <Select disabled options={sourceOptions} className='w-32 ml-2 workbenches-B620E0' />
          </Form.Item>
          <Form.Item style={{ display: 'none' }} name="targetData" label="" rules={[{ required: true, message: 'Missing targetData' }]}>
            <Select disabled options={targetOptions} className='w-32 ml-2 workbenches-B620E0' />
          </Form.Item>

          <Form.Item name="sourceTableOrSql" label="" rules={[{ required: true, message: 'Missing sourceData' }]}>
            <Select disabled options={sourceOptions} onChange={handleChange} className='w-32 ml-2 workbenches-B620E0' />
          </Form.Item>
          <Form.Item name="join" label="" rules={[{ required: true, message: 'join' }]}>
            <Select options={joinOptions} onChange={handleChange} className='w-32 ml-2 workbenches-B620E0' />
          </Form.Item>
          <Form.Item name="targetTableOrSql" label="" rules={[{ required: true, message: 'Missing targetData' }]}>
            <Select disabled options={targetOptions} onChange={handleChange} className='w-32 ml-2 workbenches-B620E0' />
          </Form.Item>
        </div>
        <Form.List name="fields">
          {(fields, { add, remove }) => (
            <>
              {fields.map(field => (
                <Space key={field.key} align="baseline">
                  <Form.Item
                    noStyle
                    shouldUpdate={(prevValues, curValues) =>
                      prevValues.sourceData !== curValues.sourceData ||
                      prevValues.fields !== curValues.fields
                    }
                  >
                    {() => (
                      <Form.Item
                        {...field}
                        label=""
                        name={[field.name, 'lField']}
                        rules={[{ required: true, message: 'Missing lField' }]}
                      >
                        <Select style={{ width: 145 }} className='ml-2 workbenches-B620E0' options={lFieldsOptions} >
                        </Select>
                      </Form.Item>
                    )}
                  </Form.Item>
                  <Form.Item
                    noStyle
                    shouldUpdate={(prevValues, curValues) =>
                      prevValues.sourceData !== curValues.sourceData ||
                      prevValues.targetData !== curValues.targetData ||
                      prevValues.fields !== curValues.fields
                    }
                  >
                    <span className='ml-2'>=</span>
                    {/* {() => (
                      <Form.Item
                        {...field}
                        label=""
                        name={[field.name, 'symbol']}
                        rules={[{ required: true, message: 'Missing symbol' }]}
                      >
                        <Select style={{ width: 80 }} className='ml-2' options={symbolOptions} >
                        </Select>
                      </Form.Item>
                    )} */}
                  </Form.Item>
                  <Form.Item
                    noStyle
                    shouldUpdate={(prevValues, curValues) =>
                      prevValues.targetData !== curValues.targetData ||
                      prevValues.fields !== curValues.fields
                    }
                  >
                    {() => (
                      <Form.Item
                        {...field}
                        label=""
                        name={[field.name, 'rField']}
                        rules={[{ required: true, message: 'Missing lField' }]}
                      >
                        <Select style={{ width: 145 }} className='ml-2 workbenches-B620E0' options={rFieldsOptions} >
                        </Select>
                      </Form.Item>
                    )}
                  </Form.Item>

                  <MinusCircleOutlined onClick={() => remove(field.name)} />
                </Space>
              ))}

              <Form.Item>
                <Button className='ml-2' type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                </Button>
              </Form.Item>
            </>
          )}
        </Form.List>
      </Form>
    </Spin>
  </Modal>
}
export default edgeModal;